package com.yinshan.voiceplay

import android.content.Context
import android.media.AudioAttributes
import android.media.SoundPool
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

/**
 * @author limh
 * @function
 * @date 2021/5/21 10:43
 */
class VoiceSpeaker private constructor(private var context: Context) {
    private val TAG = "VoiceSpeaker"

    private val threadPool = ThreadPoolExecutor(5, Integer.MAX_VALUE, 30L, TimeUnit.SECONDS, SynchronousQueue())

    private val audioAttributes: AudioAttributes = AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .build()


    companion object : SingletonHolder<VoiceSpeaker, Context>(::VoiceSpeaker)

    /**
     * 收款播报
     */
    fun playIncome(prefix: String?, message: String) {
        threadPool.execute {
            val voices = mutableListOf<Int>()
            voices.add(R.raw.suc)
            MoneyUtils.getSuffixVoice(prefix)?.let { voices.addAll(it) }
            voices.add(R.raw.prefix_income)
            voices.addAll(MoneyUtils.getMoneyVoice(message))
            voices.add(R.raw.unit_yuan)
            start(voices)
        }
    }

    /**
     * 退款播报
     */
    fun playRefund(prefix: String?, message: String) {
        threadPool.execute {
            val voices = mutableListOf<Int>()
            voices.add(R.raw.suc)
            MoneyUtils.getSuffixVoice(prefix)?.let { voices.addAll(it) }
            voices.add(R.raw.prefix_refund)
            voices.addAll(MoneyUtils.getMoneyVoice(message))
            voices.add(R.raw.unit_yuan)
            start(voices)
        }
    }

    /**
     * 订单播报
     */
    fun playOrder() {
        threadPool.execute {
            val voices = mutableListOf<Int>()
            voices.add(R.raw.new_order)
            start(voices)
        }
    }

    private fun start(voices: MutableList<Int>) {

        val soundPool = SoundPool.Builder()
            .setAudioAttributes(audioAttributes)
            .setMaxStreams(1)
            .build()
        val soundIds = mutableListOf<Int>()
        val mapSoundTime = mutableMapOf<Int, Long>()

        for (item in voices) {
            val soundId = soundPool.load(context, item, 1)
            mapSoundTime[soundId] = getVoiceDuration(item)
            soundIds.add(soundId)
        }
        var count = 0
        soundPool.setOnLoadCompleteListener { _, _, _ ->
            count++
            if (count != voices.size) {
                return@setOnLoadCompleteListener
            }
            for (i in soundIds.indices) {
                soundPool.play(soundIds[i], 1f, 1f, 1, 0, 1f)
                try {
                    Thread.sleep(mapSoundTime[soundIds[i]]!!)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }
            }
            soundPool.release()
        }
    }

    /**
     * 获取音频的时长
     */
    private fun getVoiceDuration(rawId: Int): Long {
        return when (rawId) {
            R.raw.suc -> 800
            R.raw.num_0, R.raw.num_1, R.raw.num_2, R.raw.num_3, R.raw.num_4, R.raw.num_5, R.raw.num_6,
            R.raw.num_7, R.raw.num_8, R.raw.num_9, R.raw.num_10 -> 280
            R.raw.unit_bai, R.raw.unit_qian, R.raw.unit_wan, R.raw.unit_yuan -> 350
            R.raw.point -> 350
            R.raw.prefix_income -> 500
            R.raw.prefix_refund -> 500
            R.raw.prefix_shop -> 500
            R.raw.new_order -> 3000
            else -> 0
        }
    }
}